package cn.itcast.demo;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器    exchange:获得请求上下文request,response
 *             chain:请求委托给下一个过滤器
 */
@Order(-1)      //设置运行顺序
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();  //获得请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();  //获得请求对象
        String auth = queryParams.getFirst("authrization");   //得到第一个参数
        if ("admin".equals(auth)){
            Mono<Void> filter = chain.filter(exchange);//匹配则放行，即找下一个过滤器
            return filter;
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);  //失败设置响应码
        Mono<Void> complete = exchange.getResponse().setComplete();     //失败拦截请求
        return complete;
    }
}
